package com.more.offer.threadtest.unsafetest;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author pinoc
 * @date 2021/6/21
 * @description
 */
public class UnsafeTest2 {

	public static Unsafe unsafe;

	public static long varOffset;

	public volatile long var = 0;

	//以下是unsafe的获取方法
	static{
		try {
			Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
			theUnsafe.setAccessible(true);
			unsafe = (Unsafe) theUnsafe.get(null);
			varOffset = unsafe.objectFieldOffset(UnsafeTest.class.getDeclaredField("var"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		UnsafeTest2 unsafeTest = new UnsafeTest2();
		boolean b = unsafe.compareAndSwapInt(unsafeTest, varOffset, 0, 1);
		System.out.println("result: " + b);
		String binaryString = Long.toBinaryString(6987509549724862535L);
		System.out.println(binaryString);
		long l = Long.parseLong(binaryString.substring(0, binaryString.length() - 32), 2) * 1000;
		System.out.println(l);
	}
}

